package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.mysql.jdbc.PreparedStatement;

import model.IEntity;
import model.User;

public class UserDAO implements IDAO
{
	SqlSessionFactory sqlSessionFactory;

	public UserDAO()
	{
		try
		{
			String resource = "conf.xml";

			InputStream is = Resources.getResourceAsStream(resource);

			sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public boolean addOne(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		int count = session.insert("mapper.userMapper.addOne", (User)e);
		session.commit();
		if(count>0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public boolean deleteOne(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		int count = session.delete("mapper.userMapper.deleteOne", (User)e);
		session.commit();
		if(count>0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public boolean updateOne(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		int count = session.update("mapper.userMapper.updateOne", (User)e);
		session.commit();
		if(count>0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public IEntity getOne(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		User user = session.selectOne("mapper.userMapper.getOne", (User)e);
		return user;
	}

	@Override
	public List<IEntity> getList(IEntity e)
	{
		SqlSession session = sqlSessionFactory.openSession();
		List<IEntity> users = session.selectList("mapper.userMapper.getList", (User)e);
		return users;
	}
}
